package com.group7.mall.websocket;

import com.alibaba.fastjson.JSON;
import com.group7.mall.dao.TbMessageDao;
import com.group7.mall.entity.TbMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//对外公布的一个后端站点
//ws://localhost:8080/websocket/用户id
@ServerEndpoint(value = "/websocket/{userOpenId}")
@Component
public class WebSocketEndPoint {
    //与某个客户端的连接会话，需要他来给客户端发送数据
    private Session session;

    @Autowired
    public void setTbMessageDao(TbMessageDao tbMessageDao) {
        WebSocketEndPoint.tbMessageDao = tbMessageDao;
    }

    private static TbMessageDao tbMessageDao;

    // 连接建立成功调用的方法
    @OnOpen
    public synchronized void onOpen(Session session, @PathParam("userOpenId") String userId) {
        // 把会话加入连接池中
        // userId通过用户传入，session是系统自动产生
        SessionPool.sessions.put(userId, session);
        // 从数据库中读取所有用户的所有未读消息

    }

    //关闭会话的时候
    @OnClose
    public synchronized void onClose(Session session) throws IOException {
        System.out.println("连接关闭");
        SessionPool.close(session.getId());
        session.close();
    }

    //接收客户端的消息后调用的方法，在这里可以进行各种业务逻辑的操作
    @OnMessage
    public synchronized void onMessage(String message, Session session) {
        Map<String, Object> params = JSON.parseObject(message, HashMap.class);
        String userId = params.get("fromUserId").toString();
        String toUserId = params.get("toUserId").toString();
        String msg = params.get("message").toString();
        String timeStamp = params.get("timeStamp").toString();
        String type = params.get("messageType").toString();
        TbMessage tbMessage = new TbMessage();
        tbMessage.setToUserId(toUserId);
        tbMessage.setFromUserId(userId);
        tbMessage.setMessage(msg);
        tbMessage.setTimeStamp(timeStamp);
        tbMessage.setMessageType(Integer.valueOf(type));
        try {
            UserSessionStatus.waitForChatLoaded(toUserId);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }
        Session session2 = SessionPool.sessions.get(toUserId);
        msg = userId + " " + toUserId + " " + timeStamp + " " + type + " " + msg;
        System.out.println(msg);
        if (session != null) {
            tbMessage.setIsRead(0);
        } else {
            tbMessage.setIsRead(1);
        }
        tbMessageDao.insert(tbMessage);
        SessionPool.sendMessage(params);
    }
}